let wsUrl = 'ws://localhost:7030/websocket/test/userid';
$(function(){


    // $("#sendBtn").click(function(){
    //
    //     var key = $("#sendKey").val()
    //
    //     var json = {
    //         "devType": $("#devType").val(),
    //         "devid ": $("#devid").val(),
    //         "cmd": Number($("#cmd").val()),
    //         "data": {
    //             "dtime"	: "2024.7.29 13:00:00"
    //         }
    //     }
    //
    //     json['data'][key] = $("#sendValue").val();
    //     console.log(JSON.stringify(json));
    //     websocket.send(JSON.stringify(json))
    // });
    // $("#connectBtn").click(function(){
    //     initSocket()
    //     $("#connectBtn").prop("disabled", true);
    // })

    // $("#connectBtn2").click(function(){
    //
    //     if(websocket){
    //         websocket.close();
    //         clearTimeout(st);
    //         clearTimeout(st2);
    //     }
    //
    //     $("#connectBtn").prop("disabled", false);
    // })
    /* $("#fetchBtn").click(function(){
        $.post("/websocket/calender",{
            year:$("#yearName").val()
        },function(result){
            console.log(result);
            //alert(result)
        })
    }); */

    // console.log(JSON.parse("{\"dtime\":\"2024.7.29\",\"alarm\":true,\"comstat\":true,\"doorstat\":false,\"pushrod_stat\":true,\"lockstat\":true,\"door_openlimit_stat\":false,\"door_closelimit_stat\":true,\"push_limit_stat\":true,\"pull_limit_stat\":false,\"return_stat\":true,\"operation_stat\":false,\"windspeed\":\"23\",\"UAV_stat\":true,\"UAV_power_stat\":true,\"gateway_comstat\":true,\"ethernet_comstat\":true,\"current\":\"13.6\"}"))
    initSocket()
})
function getTime(){
    const currentTime = new Date();
    const year = currentTime.getFullYear();
    const month = currentTime.getMonth() + 1; // 月份从0开始，因此需要加1
    const day = currentTime.getDate();
    const hours = currentTime.getHours();
    const minutes = currentTime.getMinutes();
    const seconds = currentTime.getSeconds();
    return year + '.' + month + '.' + day + ' ' + (hours<=9 ? ('0'+hours) : hours) + ':'+(minutes<=9 ? ('0'+minutes) : minutes)+':' + (seconds<=9 ? ('0'+seconds) : seconds);
}

function sendWsDd(sendKey,devType, devid, cmd){

    sendWs(sendKey,devType, devid, cmd , $("#jingdu").val()+','+$("#weidu").val())
}
function sendWs(sendKey,devType, devid, cmd , sendValue){

    var json = {
        "devType": devType,
        "devid ": devid,
        "cmd": Number(cmd),
        "data": {
            "dtime"	: getTime()
        }
    }

    json['data'][sendKey] = sendValue;
    console.log("发送数据:" + JSON.stringify(json));
    websocket.send(JSON.stringify(json))
}


var websocket = null;
//let url = 'ws://' + document.location.hostname + ':2200/websocket' + '/' + this.getSessionId()
function initSocket(){

    if (typeof WebSocket === 'undefined') {
        console.log('您的浏览器不支持WebSocket')
        return
    } else {


        // console.log('websocket:', url)
        // 打开一个websocket
        websocket = new WebSocket(wsUrl)
        // 建立连接
        websocket.onopen = () => {
            // 发送数据
            // this.websocket.send('发送数据')
            console.log('websocket:链接成功')
            sdheartbeat()
            heartbeat()
        }
        // 客户端接收服务端返回的数据
        websocket.onmessage = (evt) => {
            console.log('websocket返回的数据：', evt)
            var data = JSON.parse(evt.data)
            console.log(data)

            if(data.cmd == '31'){ //心跳
                console.log('心跳:' + new Date());
            }

            if(data.data){//获取data字段
                // console.log(JSON.stringify(data.data))
            }
            console.log("接收数据:" + JSON.stringify(data) );
        }
        // 发生错误时
        websocket.onerror = (evt) => {
            console.log('websocket错误：', evt)
        }
        // 关闭连接
        websocket.onclose = (evt) => {
            console.log('websocket关闭：', evt)
            // setTimeout(initSocket, 1000)
            var data = {
                "data":"client断开连接"
            }
            console.log("client断开连接:" + JSON.stringify(data));
        }
    }



}
var st = null;
var reconectTimes = 2;
function heartbeat(){
    let oldTime = new Date($("#heartbeat").html());
    let newTime = new Date();
    if(oldTime.getTime() + 1000*10 < newTime.getTime()){

        if(reconectTimes < 0){
            reconectTimes = 2;
            console.log('已到达3次，进行重连');
            clearTimeout(st);
            initSocket()
        }else{
            console.log('server心跳已超时 第' + (3 - reconectTimes) + '次');
            reconectTimes--;
        }


    }else{
        console.log('server心跳未超时');
    }
    st = setTimeout(heartbeat, 8*1000)
}

var st2 = null;
function sdheartbeat(){
    var json = {
        "devType": "0",
        "devid ": '0',
        "cmd": 31,
        "data": null
    }
    websocket.send(JSON.stringify(json))
    st2 = setTimeout(sdheartbeat, 10*1000)
}
